<template>

  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <DeptTree @node-click="handleDeptNodeClick" @node-contextmenu="openContextMenu" />
        <div v-if="showMenu && showMenuFL === 1" :style="{ top: menuY + 'px', left: menuX + 'px' }" class="context-menu">
          <ul id="menu" ref="rightmenuref" style="margin: 0px; padding: 0px;">
            <li class="menu-item" @click="openFirstForm('create')">新增分组</li>
          </ul>
        </div>
        <div v-if="showMenu && showMenuFL === 2" :style="{ top: menuY + 'px', left: menuX + 'px' }" class="context-menu">
          <ul id="menu" ref="rightmenuref" style="margin: 0px; padding: 0px;">
            <li class="menu-item" @click="openSecondForm('create')">新增表单</li>
            <li class="menu-item" @click="openFirstForm('update')">编辑分组</li>
            <li class="menu-item" @click="onDeleteForm()">删除分组</li>
          </ul>
        </div>
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="100px"
        >
          <el-form-item label="表单名称" prop="dfName">
            <el-input
              v-model="queryParams.dfName"
              placeholder="请输入表单名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="状态" prop="dfStatus">
            <el-select
              v-model="queryParams.dfStatus"
              placeholder="请选择状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="表单发布状态" prop="dfReleaseStatus">
            <el-select
              v-model="queryParams.dfReleaseStatus"
              placeholder="请选择表单发布状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_TASK_RELEASE_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column label="序号" type="index" header-align="center" align="center" width="60px" fixed />
          <el-table-column label="表单名称" align="center" prop="dfName" show-overflow-tooltip />
          <el-table-column label="状态" align="center" prop="dfStatus">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.dfStatus" />
            </template>
          </el-table-column>
          <el-table-column label="表单发布状态" align="center" prop="dfReleaseStatus">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SYSTEM_TASK_RELEASE_STATUS" :value="scope.row.dfReleaseStatus" />
            </template>
          </el-table-column>
          <el-table-column label="发布版本号" align="center" prop="dfReleaseVersion" />
          <el-table-column label="创建人" align="center">
            <template #default="scope">
              {{ userList.find((user) => user.id + '' === scope.row.creator)?.nickname }}
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button
                link
                type="primary"
                v-if="scope.row.dfReleaseStatus !== 2"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['system:form:update']"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                v-if="scope.row.dfReleaseStatus !== 2"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['system:form:delete']"
              >
                删除
              </el-button>
              <el-button
                link
                type="danger"
                v-if="scope.row.dfReleaseStatus === 2"
                @click="handleRevoke(scope.row.id)"
                v-hasPermi="['system:form:revoke']"
              >
                撤回
              </el-button>
              <el-dropdown
                @command="(command) => handleCommand(command, scope.row)"
                v-hasPermi="[
                  'system:form:develop',
                  'system:form:release',
                  'system:form:revoke'
                ]"
                v-if="scope.row.dfReleaseStatus !== 2"
              >
                <el-button type="primary" link><Icon icon="ep:d-arrow-right" /> 更多</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      command="handleDevelop"
                      v-if="checkPermi(['system:form:develop']) && scope.row.dfReleaseStatus !== 2"
                    >
                      开发
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="handleRelease"
                      v-if="checkPermi(['system:form:release']) && scope.row.dfReleaseStatus !== 2"
                    >
                      发布
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="handleRevoke"
                      v-if="checkPermi(['system:form:revoke'])"
                    >
                      撤回
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 表单弹窗：添加/修改 -->
  <FormGroupForm ref="formFirstRef" @success="getList" />

  <!-- 表单弹窗：添加/修改 -->
  <FormForm ref="formSecondRef" @success="getList" />

  <!-- 表单弹窗：开发 -->
  <FormDevelop ref="formDevelopRef" style="width: 75%;" @success="getList" />
</template>

<script setup lang="ts">
import { FormApi, FormVO } from '@/api/system/form'
import { FormGroupApi } from '@/api/system/formGroup'
import * as UserApi from '@/api/system/user'

import { getIntDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { checkPermi } from '@/utils/permission'

import FormForm from './FormForm.vue'
import FormGroupForm from './FormGroupForm.vue'
import FormDevelop from './FormDevelop.vue'
import DeptTree from './FormTree.vue'
import { pa } from 'element-plus/es/locale'

/** 表单管理 列表 */
defineOptions({ name: 'Form' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const userList = ref<UserApi.UserVO[]>([])
const showMenu = ref(false);
const showMenuFL = ref(0);
const menuX = ref(0);
const menuY = ref(0);
const level = ref(1);
const parentId = ref(0);

const list = ref<FormVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  dfName: undefined,
  dfStatus: undefined,
  dfReleaseStatus: undefined,
  dfReleaseVersion: undefined,
  parentId: undefined,
  level: 1
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await FormApi.getFormPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await FormApi.deleteForm(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 操作分发 */
const handleCommand = (command: string, row: FormVO) => {
  switch (command) {
    case 'handleDevelop':
      handleDevelop(row.id)
      break
    case 'handleRelease':
      handleRelease(row.id)
      break
    case 'handleRevoke':
      handleRevoke(row.id)
      break
    default:
      break
  }
}

/** 添加/修改操作 */
const formDevelopRef = ref()
const handleDevelop = (id?: number) => {
  formDevelopRef.value.open(id)
}

/** 发布按钮操作 */
const handleRelease = async (id: number) => {
  try {
    // 发布的二次确认
    await message.relConfirm()
    // 发起发布
    await FormApi.releaseForm(id)
    message.success(t('common.relSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 撤回按钮操作 */
const handleRevoke = async (id: number) => {
  try {
    // 撤回的二次确认
    await message.revConfirm()
    // 发起撤回
    await FormApi.revokeForm(id)
    message.success(t('common.revSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  showMenu.value = false;
  showMenuFL.value = 0;
  level.value = row.level
  queryParams.parentId = row.id
  queryParams.level = row.level
  getList()
}
 
const openContextMenu = async (event, row) => {
  closeContextMenu()
  event.preventDefault();
  document.addEventListener('click', foo) // 给整个document添加监听鼠标事件，点击任何位置执行foo方法
  if(row.level == 1) {
    // 设置菜单位置并显示
    menuX.value = event.clientX - 200;
    menuY.value = event.clientY - 120;
    showMenu.value = true;
    showMenuFL.value = 1;
    parentId.value = row.id;
  } else if(row.level == 2) {
    // 设置菜单位置并显示
    menuX.value = event.clientX - 200;
    menuY.value = event.clientY - 120;
    showMenu.value = true;
    showMenuFL.value = 2;
    parentId.value = row.id;
  }
};
// 取消鼠标监听事件 菜单栏
const foo = () => {
  showMenu.value = false;
  showMenuFL.value = 0;
  document.removeEventListener('click', foo) // 要及时关掉监听，不关掉的是一个坑，不信你试试，虽然前台显示的时候没有啥毛病，加一个alert你就知道了
};
 
const closeContextMenu = () => {
  showMenu.value = false;
  showMenuFL.value = 0;
};

/** 添加/修改操作 */
const formFirstRef = ref()
/** 添加/修改操作 */
const formSecondRef = ref()

const openFirstForm = (type: string) => {
  closeContextMenu()
  formFirstRef.value.open(type, parentId.value)
}

const openSecondForm = (type: string) => {
  closeContextMenu()
  formSecondRef.value.open(type, parentId.value)
}

/** 删除按钮操作 */
const onDeleteForm = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await FormGroupApi.deleteFormGroup(parentId.value)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(async () => {
  getList()
  userList.value = await UserApi.getSimpleUserList()
})
</script>
 
<style lang="scss">
.context-menu {
  margin: 0;
  padding: 0;
  z-index: 999;
  position: absolute;
  // height: 40px;
  width: 140px;
  position: absolute;
  border-radius: 5px;
  border: 1px solid #ccc;
  background-color: white;

  .menu-item {
    list-style: none;
    line-height: 20px;
    text-align: left;
    margin: 10px 0px;
    padding-left: 10px;
    font-size: 14px;
    color: #606266;
  }
  li:hover {
    background-color: #edf6ff;
    color: #606266;
  }
}
</style>

